class FileUploadHandler {
    constructor() {
        this.uploadArea = document.getElementById('file-upload-area');
        this.fileInput = document.getElementById('file-input');
        this.fileInfo = document.getElementById('file-info');
        this.fileName = document.getElementById('file-name');
        this.fileContentPreview = document.getElementById('file-content-preview');
        this.removeFileBtn = document.getElementById('remove-file');
        
        this.initEventListeners();
    }
    
    initEventListeners() {
        // 点击上传区域
        this.uploadArea.addEventListener('click', () => {
            this.fileInput.click();
        });
        
        // 拖拽上传
        this.uploadArea.addEventListener('dragover', (e) => {
            e.preventDefault();
            this.uploadArea.classList.add('drag-over');
        });
        
        this.uploadArea.addEventListener('dragleave', () => {
            this.uploadArea.classList.remove('drag-over');
        });
        
        this.uploadArea.addEventListener('drop', (e) => {
            e.preventDefault();
            this.uploadArea.classList.remove('drag-over');
            
            const files = e.dataTransfer.files;
            if (files.length > 0) {
                this.handleFileSelect(files[0]);
            }
        });
        
        // 文件选择变化
        this.fileInput.addEventListener('change', (e) => {
            if (e.target.files.length > 0) {
                this.handleFileSelect(e.target.files[0]);
            }
        });
        
        // 移除文件
        this.removeFileBtn.addEventListener('click', (e) => {
            e.stopPropagation();
            this.clearFile();
        });
    }
    
    async handleFileSelect(file) {
        if (!this.isValidFileType(file)) {
            alert('请选择.txt、.doc或.docx格式的文件');
            return;
        }
        
        if (file.size > 10 * 1024 * 1024) { // 10MB限制
            alert('文件大小不能超过10MB');
            return;
        }
        
        try {
            const content = await this.readFileContent(file);
            this.displayFileInfo(file.name, content);
            this.updateNovelText(content);
        } catch (error) {
            console.error('文件读取错误:', error);
            alert('文件读取失败，请重试');
        }
    }
    
    isValidFileType(file) {
        const validTypes = ['.txt', '.doc', '.docx'];
        const fileExtension = '.' + file.name.split('.').pop().toLowerCase();
        return validTypes.includes(fileExtension);
    }
    
    readFileContent(file) {
        return new Promise((resolve, reject) => {
            const reader = new FileReader();
            
            reader.onload = (e) => {
                resolve(e.target.result);
            };
            
            reader.onerror = () => {
                reject(new Error('文件读取失败'));
            };
            
            if (file.name.endsWith('.txt')) {
                reader.readAsText(file, 'UTF-8');
            } else {
                // 对于doc/docx文件，这里简单处理为文本
                // 在实际应用中，你可能需要专门的库来处理
                reader.readAsText(file);
            }
        });
    }
    
    displayFileInfo(filename, content) {
        this.fileName.textContent = filename;
        this.fileContentPreview.textContent = content.substring(0, 1000) + 
            (content.length > 1000 ? '...' : '');
        this.fileInfo.style.display = 'block';
    }
    
    updateNovelText(content) {
        const novelText = document.getElementById('novel-text');
        novelText.value = content;
        
        // 触发字数统计更新
        const event = new Event('input', { bubbles: true });
        novelText.dispatchEvent(event);
    }
    
    clearFile() {
        this.fileInput.value = '';
        this.fileInfo.style.display = 'none';
        
        // 切换到文本输入标签
        const textTabBtn = document.querySelector('[data-tab="text"]');
        textTabBtn.click();
    }
    
    getCurrentFile() {
        return this.fileInput.files[0];
    }
}

// 初始化文件上传处理
document.addEventListener('DOMContentLoaded', () => {
    new FileUploadHandler();
});